var ani = ani || {};
ani.security = ani.security || {};

function encryptMD5(src){
	return $.md5(src);
}
ani.security.UserAuthInfo = function(email, password, isSave, reqIdUrl, authInfoPostUrl){
	var _this = this;
	
	_this.email = email;
	_this.reqId = null;
	_this.isSave = isSave;
	_this.authInfoPostUrl = authInfoPostUrl;
	_this.getReqId = function(){
		$.ajaxSettings.async = false;
		$.getJSON(
			reqIdUrl,
			function(obj){
				_this.reqId = obj.data.toString();
			}
		);
		return _this.reqId;
	}
	
	_this.authCode = function(){
		//return encryptMD5(_this.email + encryptMD5(password) + _this.reqId);
		var authMessage = _this.email + encryptMD5(password);
		console.info('authMessage = ' + authMessage);
		console.info('reqId = ' + _this.reqId);
		var authCode = hex_hmac_md5(
		    _this.reqId,
		    //_this.email + encryptMD5(password)
		    authMessage
		);
		console.info('authCode = ' + authCode);
		return authCode;
	};
	
	//finally, call this function; only public function;
	_this.sendUserAuthInfo = function(){
		$.ajaxSettings.async = false;
		_this.getReqId();
		$.ajax({
			type: 'POST',
			url: authInfoPostUrl,
			data: {
				email: _this.email,
				reqId: _this.reqId,
				authCode: _this.authCode,
				isSave: _this.isSave
			},
			success: function(obj){
				_this.retData = obj;
			},
			dataType: 'json'
		});
		return _this.retData
	};
}
ani.security.authUser = function(emailId, passwordId, isSaveId, responseBoxId){
    var email = $('#' + emailId).val();
    var password = $('#' + passwordId).val();
    var isSave = $('#' + isSaveId)[0].checked;

    var userAuthInfo = new ani.security.UserAuthInfo(email, password, isSave, '/auth/reqId', '/user/login');
    var result = userAuthInfo.sendUserAuthInfo();

    var responseBox = $('#' + responseBoxId);
    if(!result.success){
        responseBox.css('display', 'block');
        responseBox.html(result.message);
    }else{
        responseBox.css('display', 'none');
        responseBox.html('');
        window.location.replace('/')
    }
}
